#include "LocalStorage.h"

// 获取单例实例
LocalStorage& LocalStorage::getInstance() {
  static LocalStorage instance;
  return instance;
}

LocalStorage::LocalStorage() {
  // 初始化 LittleFS
  if (!LittleFS.begin()) {
    Serial.println("LittleFS initialization failed!");
  } else {
    Serial.println("LittleFS initialization succeed!");
    if (LittleFS.exists(pathDir) == false) {
      if (LittleFS.mkdir(pathDir)==true) {
        Serial.println("Dir created");
      } else {
        Serial.println("mkdir failed");
      }
    }
  }
  //LittleFS.format();  //格式化文件系统--------------------------------------------------------------------------------------------------------------------------------
}

void LocalStorage::setItem(const String& key, const String& value) {
  File file = LittleFS.open(pathDir +"/"+ key, "w");
  Serial.println(pathDir +"/"+ key);
  if (file) {
    file.print(value);
    file.close();
    //Serial.println("Stored: " + key + " = " + value);
    // 更新缓存
    cacheKey = key;
    cacheValue = value;
  } else {
    Serial.println("Error opening file for writing: " + key);
  }
}

String LocalStorage::getItem(const String& key) {
  if (key == cacheKey) {
    // 从缓存中返回值
    return cacheValue;
  }

  File file = LittleFS.open(pathDir +"/"+ key, "r");
  if (file) {
    String value = file.readString();
    file.close();
    cacheKey = key;
    cacheValue = value;
    return value;
  } else {
    Serial.println("Error opening file for reading: " + key);
    return "";  // 返回空字符串或其他默认值
  }
}

void LocalStorage::removeItem(const String& key) {
  if (LittleFS.remove(pathDir +"/"+ key)) {
    Serial.println("Removed: " + key);
    // 清空缓存
    if (key == cacheKey) {
      cacheKey = "";
      cacheValue = "";
    }
  } else {
    Serial.println("Error removing file: " + key);
  }
}

void LocalStorage::clear() {
//#ifdef ESP32
  LittleFS.format();  //格式化文件系统
/*#elif defined(ESP8266)
  Dir dir = LittleFS.openDir(pathDir);
  while (dir.next()) {
    String fileName = dir.fileName();
    LittleFS.remove(pathDir +"/"+ fileName);
    Serial.println("\nRemoved: " + fileName);
  }
#endif*/
  Serial.println("Cleared all storage.");
  // Clear the cache
  cacheKey = "";
  cacheValue = "";
}
